package com.candy.candyuser.extend;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.sql.Statement;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Properties;

/**
 * @author suYanLong
 * @date 2023年02月10日 17:12
 */
@Slf4j
@Component
@Intercepts({@Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class})})
public class ResultSetInterceptor implements Interceptor {

    @Autowired
    IDecryptUtil iDecryptUtil;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        Object object = invocation.proceed();
        if (object instanceof ArrayList) {
            ArrayList<Objects> returnList = (ArrayList<Objects>) object;
            if (!CollectionUtils.isEmpty(returnList) && needToDecrypt(returnList.get(0))) {
                for (Object result : returnList) {
                    iDecryptUtil.decrypt(result);
                }
            }
        } else {
            if (needToDecrypt(object)) {
                iDecryptUtil.decrypt(object);
            }
        }
        return object;
    }

    private boolean needToDecrypt(Object obj) {
        Class<?> aClass = obj.getClass();
        SensitiveData annotation = AnnotationUtils.findAnnotation(aClass, SensitiveData.class);
        return Objects.nonNull(annotation);
    }

    @Override
    public Object plugin(Object target) {
        return Interceptor.super.plugin(target);
    }

    @Override
    public void setProperties(Properties properties) {
        Interceptor.super.setProperties(properties);
    }

}
